<template>
  <div class="layout">
    <!-- 侧边导航栏 -->
    <ExerciseTopBar class="sidebar"
      @action="handleAction" 
      :userRole="userRole"
      :userId="userId"
      :courseId="courseId"
    />
    <!-- 动态加载内容区域 -->
    <div class="content-area">
      <!-- 添加页面切换动画 -->
      <transition name="slide-fade" mode="out-in">
        <component
          :key="currentView" 
          :is="currentView" 
          class="content-container"
          :userId="userId" 
          :courseId="courseId"
          :userRole="userRole" 
          :classes="getComponentClasses"  
        ></component>
      </transition>
    </div>
  </div>
</template>

<script>
import ExerciseTopBar from '../components/exercise/ExerciseTopBar.vue';
import UnfinishedExercise from '../components/exercise/UnfinishedExercise.vue';
import FinishedExercise from '../components/exercise/FinishedExercise.vue';
import CollectingExercise from '../components/exercise/CollectingExercise.vue';
import WrongExercise from '../components/exercise/WrongExercise.vue';
import AddExercise from '../components/exercise/AddExercise.vue';
import GradeExercise from '../components/exercise/GradeExercise.vue';
import DeleteExercise from '@/components/exercise/DeleteExercise.vue';
import ExerciseBank from '../components/exercise/ExerciseBank.vue';
import { useUserStore } from '@/stores/userStore';
import { useRoute } from 'vue-router';
import request from '@/utils/request';

export default {
  name: 'ExerciseCenter',
  components: {
    ExerciseTopBar,
    UnfinishedExercise,
    FinishedExercise,
    CollectingExercise,
    WrongExercise,
    AddExercise,
    GradeExercise,
    DeleteExercise,
    ExerciseBank
  },
  data() {
    return {
      currentView: '',
      userRole: '',
      userId: '',
      courseId: '',
      classesId: '',
      teacherClasses: []
    };
  },
  computed: {
    isTeacher() {
      return this.userRole === 'teacher';
    },
    getComponentClasses() {
      if (this.isTeacher) {
        return this.teacherClasses;
      } else {
        return this.classesId ? [{ classesId: this.classesId }] : [];
      }
    }
  },
  mounted: async function() {
    try {
      const userStore = useUserStore();
      const route = useRoute();
      this.courseId = route.params.id;
      this.userId = userStore.user?.userId;

      const userRoleResponse = await request.get('/api/exercises/role', {
        params: { courseId: this.courseId, userId: this.userId }
      });
      // 后端返回的是 {role: "student"} 或 {role: "teacher"} 格式
      this.userRole = userRoleResponse.role || 'undefined';
      this.setDefaultViewByRole(this.userRole);

      if (this.isTeacher) {
        try {
          // 先尝试获取指定课程的班级
          console.log('尝试获取课程特定班级...');
          const response = await request.get(`/api/classes/course/${this.courseId}/teacher/${this.userId}`);
          let teacherClasses = [];
          
          // 检查响应格式，适应不同的API返回结构
          if (response && response.data) {
            teacherClasses = response.data; // 如果返回包含data字段
          } else if (Array.isArray(response)) {
            teacherClasses = response; // 如果直接返回数组
          }
          
          if (Array.isArray(teacherClasses) && teacherClasses.length > 0) {
            this.teacherClasses = teacherClasses.map(cls => ({
              classesId: cls.classesId,
              classesName: cls.classesName
            }));
            console.log('成功获取到课程特定班级:', this.teacherClasses);
          } else {
            console.log('未找到课程特定班级，尝试获取所有班级...');
            // 如果没有找到，则获取所有班级
            const allClassesResponse = await request.get('/api/classes');
            let allClasses = [];
            
            // 同样检查响应格式
            if (allClassesResponse && allClassesResponse.data) {
              allClasses = allClassesResponse.data;
            } else if (Array.isArray(allClassesResponse)) {
              allClasses = allClassesResponse;
            }
            
            if (Array.isArray(allClasses) && allClasses.length > 0) {
              this.teacherClasses = allClasses.map(cls => ({
                classesId: cls.classesId,
                classesName: cls.classesName
              }));
              console.log('成功获取到所有班级:', this.teacherClasses);
            } else {
              console.warn('未找到任何班级数据');
            }
          }
        } catch (error) {
          console.error('获取班级列表失败:', error?.response?.data || error?.message || error);
          // 出错时尝试备用方法获取所有班级
          try {
            console.log('尝试备用方法获取所有班级...');
            const backupResponse = await request.get('/api/classes');
            let backupClasses = [];
            
            if (backupResponse && backupResponse.data) {
              backupClasses = backupResponse.data;
            } else if (Array.isArray(backupResponse)) {
              backupClasses = backupResponse;
            }
            
            if (Array.isArray(backupClasses) && backupClasses.length > 0) {
              this.teacherClasses = backupClasses.map(cls => ({
                classesId: cls.classesId,
                classesName: cls.classesName
              }));
              console.log('备用方法成功获取到班级:', this.teacherClasses);
            }
          } catch (backupError) {
            console.error('备用方法获取班级也失败:', backupError);
          }
        }
      } else {
        const classesId = await request.get(`/api/classes/course/${this.courseId}/user/${this.userId}/id`);
        this.classesId = classesId;
      }
    } catch (error) {
      console.error('API 请求失败:', error.response?.data || error.message);
      if (error.response?.status === 500) {
        alert('班级信息获取失败，请检查是否已加入班级');
      }
    }
  },
  methods: {
    handleAction({ type }) {
      const viewMap = {
        'unfinishedExercise': 'UnfinishedExercise',
        'finishedExercise': 'FinishedExercise',
        'collectingExercise': 'CollectingExercise',
        'wrongExercise': 'WrongExercise',
        'addExercise': 'AddExercise',
        'gradeExercise': 'GradeExercise',
        'deleteExercise': 'DeleteExercise',
        'exerciseBank': 'ExerciseBank'
      };
      if (viewMap[type]) {
        this.currentView = viewMap[type];
      }
    },
    setDefaultViewByRole(role) {
      switch (role) {
        case 'student':
          this.currentView = 'UnfinishedExercise';
          break;
        case 'teacher':
          this.currentView = 'AddExercise';
          break;
        default:
          this.currentView = '';
      }
    }
  }
};
</script>

<style scoped>
.layout {
  display: flex;
  min-height: 100vh;
}

.sidebar {
  width: 250px;
  min-height: 100vh;
  background-color: #f8f9fa;
  border-right: 1px solid #e0e0e0;
  box-shadow: 0 2px 4px rgba(0,0,0,0.05);
  z-index: 10;
  transition: transform 0.3s ease;
}

.content-area {
  flex: 1;
  min-height: 100vh;
  overflow: auto;
  background-color: #ffffff;
  position: relative;
}

.content-container {
  padding: 2rem;
  max-width: 1200px;
  margin: 0 auto;
  width: 100%;
}

/* 页面切换动画 */
.slide-fade-enter-active {
  animation: slide-fade-in 0.3s ease-out;
}

.slide-fade-leave-active {
  animation: slide-fade-out 0.3s ease-in;
}

@keyframes slide-fade-in {
  0% {
    transform: translateX(-20px);
    opacity: 0;
  }
  100% {
    transform: translateX(0);
    opacity: 1;
  }
}

@keyframes slide-fade-out {
  0% {
    transform: translateX(0);
    opacity: 1;
  }
  100% {
    transform: translateX(20px);
    opacity: 0;
  }
}

/* 移动端响应式样式 */
@media (max-width: 768px) {
  .layout {
    flex-direction: column;
  }
  
  .sidebar {
    width: 100%;
    min-height: auto;
    border-right: none;
    border-bottom: 1px solid #e0e0e0;
    position: sticky;
    top: 0;
  }
  
  .content-area {
    min-height: auto;
    overflow: visible;
  }
  
  .content-container {
    padding: 1.5rem 1rem;
  }
}
</style>